import 'dart:convert';

import 'package:city_pickers/city_pickers.dart';
import 'package:city_pickers/modal/result.dart';
import 'package:common_utils/common_utils.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_picker/picker.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_switch/flutter_switch.dart';
import 'package:provider/provider.dart';
import 'package:taonile/config/config.dart';
import 'package:taonile/utils/double_utils.dart';

import '../entity/bank_list_entity.dart';
import '../entity/user_info_entity.dart';
import '../http/api.dart';
import '../provider/userinfo_provider.dart';
import '../routers/routers.dart';
import '../utils/count_down_time_util.dart';
import '../utils/string_utils.dart';
import '../views/dialog_manager.dart';

///
/// 提现
///
class MineGetCash extends StatefulWidget {
  var amount = '';

  MineGetCash({Key? key, this.amount = '0.00'}) : super(key: key);

  @override
  State<MineGetCash> createState() => _MineGetCashState();
}

class _MineGetCashState extends State<MineGetCash> {
  late UserInfoEntity infoEntity;
  var _num = '';
  List<BankListDataData> datas = [];
  var bankName = '请选择银行卡';
  var bankId = '';
  String captcha = '';
  String codeTips = '获取验证码';
  bool isGetCode = true;
  double withdrawalFees = 10;
  String realFee = '0';
  String withdrawal_instructions ='';
  @override
  void initState() {
    super.initState();
    getdatas();
    getFees();
  }

  confirm() {
    FocusManager.instance.primaryFocus?.unfocus();

    if (bankName == '请选择银行卡') {
      EasyLoading.showToast("请选择提现银行卡");
      return;
    }

    if (_num.isEmpty) {
      EasyLoading.showToast("请输入提现金额");
      return;
    }

    if (!StringUtils.isFloatNum(_num)) {
      EasyLoading.showToast("请输入正确的提现金额");
      return;
    }

    if (captcha.length < 6) {
      EasyLoading.showToast("请输入6位验证码");
      return;
    }

    DialogManager.showDefaultDialog(context, "确认提现", () {
      getCash();
    });
  }

  getdatas() async {
    dynamic result = await Api.bankCardList({'page': '1', 'limit': '20'});
    BankListEntity entity = BankListEntity.fromJson(result);
    setState(() {
      datas.clear();
      datas.addAll(entity.data.data);
    });
  }

  getFees() async {
    dynamic result = await Api.getSystemConfig();
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      String feestr = jsonResult['data']['withdrawal_fees'];
      withdrawalFees = double.parse(feestr);

      setState(() {
        withdrawal_instructions = jsonResult['data']['withdrawal_instructions'];
      });
    }
  }

  getRealFee() {
    double a = 0;
    try {
      double inputNum = double.parse(_num);
      a = inputNum * (withdrawalFees / 100);
    } catch (e) {
      print(e);
    }
    setState(() {
      realFee = DoubleUtils.formartNum(a, 2);
    });
  }

  sendSms(String mobile) async {
    if (mobile.length < 11) {
      return;
    }
    dynamic result = await Api.sendSms({'mobile': mobile});
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      EasyLoading.showToast("验证码已发送，请注意查看短信");
    }
  }

  getCash() async {
    dynamic result = await Api.getCash({'money': _num, 'account_id': bankId, 'captcha': captcha});
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      EasyLoading.showToast("提现成功");
      // dynamic users = await Api.getUserinfo();
      // Map<String, dynamic> resultUsers = Map.from(users);
      // UserInfoEntity infoEntity = UserInfoEntity.fromJson(resultUsers);
      // Provider.of<UserInfoProvider>(context, listen: false).changeUserinfo(infoEntity);
      Routes.router.pop(context, {'result': 1});
    }
  }

  chooseBank(BuildContext context) async {
    Picker(
        adapter: PickerDataAdapter(
            pickerData: List.generate(
                datas.length,
                (index) =>
                    '${datas[index].bankName}-${datas[index].bankBranch}(${StringUtils.getBankCardEndNum(datas[index].bankNumber)})'),
            isArray: false),
        height: 450.w,
        headerDecoration: BoxDecoration(
          color: Config.colorWhite,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20.w),
            topRight: Radius.circular(20.w),
          ),
        ),
        itemExtent: 70.w,
        confirmText: '确定',
        cancelText: '取消',
        columnPadding: EdgeInsets.all(15.w),
        onConfirm: (picker, list) {
          // LogUtil.v(SingletonManager.instance.orderCancelReason[list[0]]);
          setState(() {
            bankName =
                '${datas[list[0]].bankName}-${datas[list[0]].bankBranch}(${StringUtils.getBankCardEndNum(datas[list[0]].bankNumber)})';
            bankId = datas[list[0]].id;
          });
        }).showModal(context, backgroundColor: Colors.transparent);
  }

  @override
  Widget build(BuildContext context) {
    infoEntity = Provider.of<UserInfoProvider>(context).userInfo;
    return Scaffold(
      backgroundColor: Config.colorBg2,
      appBar: AppBar(
        title: const Text('提现'),
        centerTitle: true,
        actions: <Widget>[
          TextButton(
            child: Text(
              '提现记录',
              style: TextStyle(color: Config.colorText1, fontSize: 26.w),
            ),
            onPressed: () {
              Routes.navigateTo(context, Routes.mineGetCashRecord).then((value) {});
            },
          ),
        ],
      ),
      body: Container(
        width: double.infinity,
        margin: EdgeInsets.symmetric(vertical: 25.w, horizontal: 25.w),
        height: double.infinity,
        child: SingleChildScrollView(
          child: Column(
            children: [
              Container(
                width: double.infinity,
                height: 140.w,
                padding: EdgeInsets.symmetric(vertical: 25.w, horizontal: 25.w),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(12.w),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "可用提现金额",
                      style: TextStyle(fontSize: 24.sp, color: Config.colorText1),
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 8.w),
                    ),
                    Row(
                      children: [
                        Text(
                          widget.amount,
                          style: TextStyle(
                              fontSize: 28.sp,
                              color: Config.colorMain,
                              fontWeight: FontWeight.bold),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 5.w),
                        ),
                        Text(
                          '金券',
                          style: TextStyle(
                              fontSize: 27.sp,
                              color: Config.colorMain,
                              fontWeight: FontWeight.bold),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              Container(
                width: double.infinity,
                padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 20.w),
                margin: EdgeInsets.only(top: 25.w),
                decoration: BoxDecoration(
                  color: (Config.colorWhite),
                  borderRadius: BorderRadius.circular(10.w),
                ),
                child: Column(
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          margin: EdgeInsets.symmetric(vertical: 5.w),
                          width: 140.w,
                          child: Text(
                            "提现银行卡",
                            style: TextStyle(fontSize: 25.sp),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 30.w),
                        ),
                        InkWell(
                          onTap: () {
                            if (datas.isEmpty) {
                              EasyLoading.showToast('请先添加银行卡');
                              return;
                            }
                            chooseBank(context);
                          },
                          child: Container(
                            width: 450.w,
                            margin: EdgeInsets.symmetric(vertical: 5.w),
                            child: Text(
                              bankName,
                              style: TextStyle(fontSize: 25.sp),
                            ),
                          ),
                        ),
                        Icon(
                          Icons.arrow_forward_ios,
                          size: 25.w,
                        ),
                      ],
                    ),
                    Divider(
                      color: Config.colorDivider,
                      height: 40.w,
                      thickness: 2.w,
                    ),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          margin: EdgeInsets.symmetric(vertical: 5.w),
                          width: 140.w,
                          child: Text(
                            "提现金额",
                            style: TextStyle(fontSize: 25.sp),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 30.w),
                        ),
                        Row(
                          children: [
                            Container(
                              width: 380.w,
                              margin: EdgeInsets.symmetric(vertical: 5.w),
                              child: TextField(
                                keyboardType: TextInputType.number,
                                textAlign: TextAlign.justify,
                                obscureText: false,
                                maxLength: 10,
                                maxLines: 1,
                                onChanged: (value) {
                                  setState(() {
                                    _num = value;
                                    getRealFee();
                                  });
                                },
                                inputFormatters: [
                                  FilteringTextInputFormatter.allow(RegExp("[0-9.]")),
                                ],
                                style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                                decoration: const InputDecoration(
                                  hintStyle: TextStyle(color: Config.colorText3),
                                  hintText: "请输入提现金额",
                                  counterText: '',
                                  isDense: true,
                                  border: InputBorder.none,
                                  contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                                ),
                              ),
                            ),
                            Container(
                              width: 100.w,
                              alignment: Alignment.centerRight,
                              child: Text(
                                "金券",
                                style: TextStyle(fontSize: 25.sp),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                    Divider(
                      color: Config.colorDivider,
                      height: 40.w,
                      thickness: 2.w,
                    ),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          margin: EdgeInsets.symmetric(vertical: 5.w),
                          width: 140.w,
                          child: Text(
                            "提现手续费",
                            style: TextStyle(fontSize: 25.sp),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 30.w),
                        ),
                        Container(
                          width: 480.w,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                realFee,
                                style: TextStyle(fontSize: 25.sp),
                              ),
                              Text(
                                '$withdrawalFees%',
                                style: TextStyle(fontSize: 25.sp),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                    Divider(
                      color: Config.colorDivider,
                      height: 40.w,
                      thickness: 2.w,
                    ),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          margin: EdgeInsets.symmetric(vertical: 5.w),
                          width: 140.w,
                          child: Text(
                            "绑定手机号",
                            style: TextStyle(fontSize: 25.sp),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 30.w),
                        ),
                        Text(
                          infoEntity.data.mobile,
                          style: TextStyle(fontSize: 25.sp),
                        ),
                      ],
                    ),
                    Divider(
                      color: Config.colorDivider,
                      height: 40.w,
                      thickness: 2.w,
                    ),
                    Row(
                      children: [
                        Container(
                          margin: EdgeInsets.symmetric(vertical: 5.w),
                          width: 140.w,
                          child: Text(
                            "验证码",
                            style: TextStyle(fontSize: 25.sp),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 30.w),
                        ),
                        Container(
                          width: 360.w,
                          margin: EdgeInsets.symmetric(vertical: 8.w),
                          child: TextField(
                            keyboardType: TextInputType.number,
                            textAlign: TextAlign.justify,
                            obscureText: false,
                            maxLength: 6,
                            maxLines: 1,
                            onChanged: (value) {
                              setState(() {
                                captcha = value;
                              });
                            },
                            style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                            decoration: const InputDecoration(
                              hintStyle: TextStyle(color: Config.colorText3),
                              hintText: "请输入验证码",
                              counterText: '',
                              isDense: true,
                              border: InputBorder.none,
                              contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                            ),
                          ),
                        ),
                        InkWell(
                          onTap: () {
                            if (!isGetCode) {
                              return;
                            }
                            sendSms(infoEntity.data.mobile);
                            CountDownTimeUtil(60, 1, (int currentTime) {
                              var _currentTime = currentTime;
                              setState(() {
                                if (_currentTime == 0) {
                                  codeTips = '获取验证码';
                                  isGetCode = true;
                                } else {
                                  codeTips = '$_currentTime';
                                }
                              });
                            });
                            isGetCode = false;
                          },
                          child: Text(
                            codeTips,
                            style: TextStyle(
                              color: Config.colorMain,
                              fontSize: 22.sp,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 30.w),
                alignment: Alignment.centerLeft,
                child: Text(
                  withdrawal_instructions,
                  style: TextStyle(fontSize: 25.sp, color: Config.colorText3),
                ),
              ),
              Container(
                width: 750.w,
                height: 100.w,
                padding: EdgeInsets.symmetric(vertical: 8.w, horizontal: 8.w),
                margin: EdgeInsets.only(top: 45.w),
                child: ElevatedButton(
                  clipBehavior: Clip.antiAlias,
                  onPressed: () => {confirm()},
                  style: ElevatedButton.styleFrom(shape: const StadiumBorder()),
                  child: const Text('确认提现'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
